/**
 * 
 */
package edu.umd.clip.lm.util;

import org.w3c.dom.*;
import java.util.*;
/**
 * @author Denis Filimonov <den@cs.umd.edu>
 *
 */
public class XMLUtils {

	public static class NodeListImpl implements NodeList {
		private List<Node> nodes;
		
		private NodeListImpl(List<Node> nodes) {
			this.nodes = nodes;
		}
		/* (non-Javadoc)
		 * @see org.w3c.dom.NodeList#getLength()
		 */
		public int getLength() {
			return nodes.size();
		}

		/* (non-Javadoc)
		 * @see org.w3c.dom.NodeList#item(int)
		 */
		public Node item(int index) {
			return nodes.get(index);
		}
		
	}
	
	public static NodeList getChildrenElementsByTagName(Element node, String tag) {
		NodeList children = node.getChildNodes();
		ArrayList<Node> list = new ArrayList<Node>(); 
		for(int i=0; i<children.getLength(); ++i) {
			Node n = children.item(i);
			if (n.getNodeType() != Node.ELEMENT_NODE) continue;
			if (((Element)n).getTagName().equals(tag)) {
				list.add(n);
			}
		}
		return new NodeListImpl(list);
	}
	
	public static Element getFirstElementByTagName(Element node, String tag) {
		NodeList children = node.getChildNodes();
		for(int i=0; i<children.getLength(); ++i) {
			Node n = children.item(i);
			if (n.getNodeType() == Node.ELEMENT_NODE && ((Element)n).getTagName().equals(tag)) {
				return (Element)n;
			}
		}
		return null;
	}
}
